import os
import sys

from PySide6.QtCore import Qt
from PySide6.QtWidgets import QFileDialog, QMessageBox, QWidget

from ..config import ExcelConfig, R
from ..core.excel import ExcelAccount, ExcelSale
from .fill_category_ui import Ui_Form


class FillCategoryWidget(QWidget):
    def __init__(self) -> None:
        super().__init__()
        self.ui = Ui_Form()
        self.ui.setupUi(self)
        self.ui.pushButton_SelectFile.clicked.connect(self.SelectOrgFile)
        self.ui.pushButton_SelectSaleTemplateFile.clicked.connect(
            self.SelectSaleTemplateFile
        )
        self.ui.pushButton_SelectAccountTemplateFile.clicked.connect(
            self.SelectAccountTemplateFile
        )
        self.ui.pushButton_FillCategory.clicked.connect(self.FillCategory)
        self.ui.pushButton_GenerateSales.clicked.connect(self.GenerateSales)
        self.ui.pushButton_GenerateAccount.clicked.connect(self.GenerateAccount)
        self.InitUi()
        self.filename = os.path.join(os.path.expanduser('~'), 'Desktop')  #"."

    def InitUi(self):
        self.ui.lineEdit_FileName.setText(R.F_Filename)
        self.ui.lineEdit_SaleTemplateFileName.setText(R.F_SaleTemplateFilename)
        self.ui.lineEdit_AccountTemplateFileName.setText(R.F_AccountTemplateFilename)
        self.ui.lineEdit_SaleSheetName.setText(R.F_SaleSheetName)
        self.ui.lineEdit_BackSheetName.setText(R.F_BackSheetName)
        self.ui.lineEdit_SaleBackCategoryCol.setText(R.F_SaleBackCategoryCol)
        self.ui.lineEdit_OrgSheetName.setText(R.F_OrgSheetName)
        self.ui.lineEdit_OrgClientRow.setText(R.F_OrgClientRow)
        self.ui.lineEdit_OrgCategoryCol.setText(R.F_OrgCategoryCol)
        self.ui.lineEdit_OrgDateCol.setText(R.F_OrgDateCol)
        self.ui.lineEdit_OrgStartRow.setText(R.F_OrgStartRow)
        self.ui.lineEdit_OrgEndRow.setText(R.F_OrgEndRow)
        self.ui.lineEdit_OrgStartCol.setText(R.F_OrgStartCol)
        self.ui.lineEdit_OrgEndCol.setText(R.F_OrgEndcol)

    def SelectOrgFile(self):
        filename, ext = QFileDialog.getOpenFileName(
            self,
            "OpenFile",
            os.path.dirname(self.filename),
            "Excel File (*.xlsx);; All File (*.*)",
        )
        if filename:
            self.ui.lineEdit_FileName.setText(filename)
            self.filename = filename
        else:
            QMessageBox.about(self, "Open file", "No opened file!")

    def SelectSaleTemplateFile(self):
        filename, ext = QFileDialog.getOpenFileName(
            self,
            "OpenFile",
            os.path.dirname(self.filename),
            "Excel File (*.xlsx);; All File (*.*)",
        )
        if filename:
            self.ui.lineEdit_SaleTemplateFileName.setText(filename)
            self.filename = filename
        else:
            QMessageBox.about(self, "Open file", "No opened file!")

    def SelectAccountTemplateFile(self):
        filename, ext = QFileDialog.getOpenFileName(
            self,
            "OpenFile",
            os.path.dirname(self.filename),
            "Excel File (*.xlsx);; All File (*.*)",
        )
        if filename:
            self.ui.lineEdit_AccountTemplateFileName.setText(filename)
            self.filename = filename
        else:
            QMessageBox.about(self, "Open file", "No opened file!")

    def FillCategory(self):
        try:
            filename = self.ui.lineEdit_FileName.text()
            saleSheetName = self.ui.lineEdit_SaleSheetName.text()
            backSheetName = self.ui.lineEdit_BackSheetName.text()
            saleBackCategoryCol = int(self.ui.lineEdit_SaleBackCategoryCol.text())
            orgSheetName = self.ui.lineEdit_OrgSheetName.text()
            orgClientRow = int(self.ui.lineEdit_OrgClientRow.text())
            orgCategoryCol = int(self.ui.lineEdit_OrgCategoryCol.text())
            orgDateCol = int(self.ui.lineEdit_OrgDateCol.text())
            orgStartRow = int(self.ui.lineEdit_OrgStartRow.text())
            orgEdnRow = int(self.ui.lineEdit_OrgEndRow.text())
            orgStartCol = int(self.ui.lineEdit_OrgStartCol.text())
            orgEndCol = int(self.ui.lineEdit_OrgEndCol.text())

            """
            填充销售销退类别
            """
            sale = ExcelSale()
            sale.open(filename)

            if saleSheetName != '' and saleSheetName is not None:
                sale.fill_category(
                    x_sheetname=saleSheetName,
                    x_category_col=saleBackCategoryCol,
                    org_sheetname=orgSheetName,
                    org_client_row=orgClientRow,
                    org_date_col=orgDateCol,
                    org_category_col=orgCategoryCol,
                    org_start_row=orgStartRow,
                    org_end_row=orgEdnRow,
                    org_start_col=orgStartCol,
                    org_end_col=orgEndCol,
                    is_xt=False    # False: 销售
                )  

            if backSheetName != '' and backSheetName is not None:
                sale.fill_category(
                    x_sheetname=backSheetName,
                    x_category_col=saleBackCategoryCol,
                    org_sheetname=orgSheetName,
                    org_client_row=orgClientRow,
                    org_date_col=orgDateCol,
                    org_category_col=orgCategoryCol,
                    org_start_row=orgStartRow,
                    org_end_row=orgEdnRow,
                    org_start_col=orgStartCol,
                    org_end_col=orgEndCol,
                    is_xt=True   # True: 销退
                )  
            sale.save(filename)
            self.filename = filename

            QMessageBox.about(self, R.AppName, "填充类别成功！")

        except Exception as e:
            QMessageBox.about(self, R.AppName, f"请填充正确的数字！Errors: {e}")

    def GenerateSales(self):
        try:
            filename = self.ui.lineEdit_FileName.text()
            sale_template_filename = self.ui.lineEdit_SaleTemplateFileName.text()
            sale_sheetname = self.ui.lineEdit_SaleSheetName.text()
            back_sheetname = self.ui.lineEdit_BackSheetName.text()

            """ 生成销售确认函 """
            sale = ExcelSale()
            sale.open(filename)

            sale.gen_sales(
                sale_sheetname, back_sheetname, sale_template_filename
            )  # , changed_catgory='教材教辅')    # changed_category=None 取消修改类别

            QMessageBox.about(self, R.AppName, "生成确认函成功！")

        except Exception as e:
            QMessageBox.about(self, R.AppName, f"请填充正确的数字！Errors: {e}")

    def GenerateAccount(self):
        try:
            filename = self.ui.lineEdit_FileName.text()
            account_template_filename = self.ui.lineEdit_AccountTemplateFileName.text()
            sale_sheetname = self.ui.lineEdit_SaleSheetName.text()
            back_sheetname = self.ui.lineEdit_BackSheetName.text()

            """ 生成做账明细 """
            exl: ExcelAccount = ExcelAccount(
                org_path=filename, dest_path=account_template_filename
            )
            
            xs_config = xt_config = None 
            if sale_sheetname != '' and sale_sheetname is not None:
                xs_config = ExcelConfig(
                    sheet_name=sale_sheetname,
                    client_id=4,
                    client_name=5,
                    number=7,
                    amount=8,
                    category=9,
                    start_row=3,
                    end_row=3000,
                )
            if back_sheetname != '' and back_sheetname is not None:
                xt_config = ExcelConfig(
                    sheet_name=back_sheetname,
                    client_id=4,
                    client_name=5,
                    number=7,
                    amount=8,
                    category=9,
                    start_row=3,
                    end_row=1200,
                )
            dest_config = ExcelConfig(
                sheet_name="账目",
                client_name=7,
                amount=5,
                number=10,
                start_row=3,
                category=3,
            )
            exl.config(
                xs_config=xs_config, xt_config=xt_config, dest_config=dest_config
            )

            exl.fill()

            QMessageBox.about(self, R.AppName, "生成账目成功！")

        except Exception as e:
            QMessageBox.about(self, R.AppName, f"请填充正确的数字！Errors: {e}")
